package com.my.util;

import com.my.bean.*;
import com.my.controller.WorkguidaceController;
import org.apache.log4j.Logger;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.io.File;
import java.util.Date;

/**
 * Created by Zhang on 2018/10/8.
 */
public class FileUpload {
    static Logger logger=Logger.getLogger(FileUpload.class);

    /**
     *
     * @param file  文件
     * @return 上传成功返回 上传后的路径
     * @throws FileNotFoundException
     */
    public static  String fileUpload(  MultipartFile file) throws FileNotFoundException {
        if(file.isEmpty()){
            return "false";
        }
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();

        System.out.println(fileName + "-->" + size);

        //String path = "F:/test" ;
        File path   = new File(ResourceUtils.getURL("classpath:").getPath());
        String  filePath=path.getParentFile().getParentFile()+File.separator+"uploads"+File.separator;
       String fiilePath=getJarRootPath()+"/uploads/"+new Date().getTime()+fileName;
        File dest = new File(fiilePath);
        if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest); //保存文件
            return  fiilePath ;
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 文件下载
     * @param response
     * @return
     */
    public static String downLoad(HttpServletResponse response, com.my.bean.File myFile) throws UnsupportedEncodingException {

        //获取文件名
        String fileName=getFileName(myFile);
        File file = new File(myFile.getUrl());
        if(file.exists()){ //判断文件父目录是否存在
            response.setContentType("application/force-download;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;fileName="   + new String(fileName.getBytes("UTF8"), "iso-8859-1")   );

            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;

            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("----------file download" + fileName);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }
    private static String getJarRootPath() throws FileNotFoundException {
        String path = ResourceUtils.getURL("classpath:").getPath();
        //=> file:/root/tmp/demo-springboot-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/
        logger.info("ResourceUtils.getURL(\"classpath:\").getPath() -> "+path);
        //创建File时会自动处理前缀和jar包路径问题 => /root/tmp
        File rootFile = new File(path);
        if(!rootFile.exists()) {
            logger.info("根目录不存在, 重新创建");
            rootFile = new File("");
            logger.info("重新创建的根目录: "+rootFile.getAbsolutePath()); }
        logger.info("项目根目录: "+rootFile.getAbsolutePath());
        //获取的字符串末尾没有分隔符 /
        return rootFile.getAbsolutePath();
    }

    //删除单个文档
    public static boolean deleteFile(String url) {
        File file = new File(url);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                return true;
            } else {
                return false;
            }
        } else {

            return false;
        }
    }
    /**
     * 根据上传完成后的文件路径  获取文件名
     * @param myFile
     * @return
     */
    public static  String getFileName(com.my.bean.File myFile ){
        String url=myFile.getUrl();
        //截取uploads文件夹
        String[] sourceStrArray =  url.split("uploads");
        //去掉文件夹后的/
        String fileName=sourceStrArray[1].substring(1);
        return  fileName;
    }
}
